package com.security;

import com.alibaba.fastjson.JSON;
import com.pojo.vo.OtpVo;
import com.util.OtpUtils;
import lombok.extern.log4j.Log4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service

public class OtpService {
    @Resource(name = "jsonRedisTemplate")
    private RedisTemplate redisTemplate;
    static final String OTP_PREFIX = "otp-";

    //发送otp到redis
    public void sendOtp(String username) {
        String code = OtpUtils.generateOtp();
        OtpVo otpVo = new OtpVo(code, OTP_PREFIX + username, new Date().getTime(), OtpVo.DETAUL_OPT_EXIPRE);
        //将otp对象存入redis
        redisTemplate.opsForValue().set(OTP_PREFIX + username, otpVo, OtpVo.DETAUL_OPT_EXIPRE, TimeUnit.MINUTES);
        //异步发送:将消息发送到消息队列，监听器收到消息后发送短信
    }

    //验证otp密码的正确性
    public boolean checkOtp(String username, String code) {
        if (redisTemplate.hasKey(OTP_PREFIX + username)) {
            OtpVo otpVo = (OtpVo) redisTemplate.opsForValue().get(OTP_PREFIX + username);
            if (otpVo.getExpireTime() > new Date().getTime() && code.equals(otpVo.getCode()))
                return true;
        }
        return false;
    }
}
